<template>
  <div v-loading="loading" class="log-list-container">
    <div class="title-container">
      <div><Title title="上传记录" /></div>
      <span v-if="logData.total" class="total">（共{{ logData.total }}条记录）</span>
    </div>
    <div :class="{'mobile-table mobile-pt mobile-min-height':showMobilePage}" class="table">
      <u-table
        v-if="logData.items && logData.items.length > 0"
        ref="tableRef"
        :data="logData.items"
        :expand-row-keys="expandRowKeys"
        :border="true"
        :row-height="rowHeight()"
        beautify-table
        header-drag-style
        use-virtual
        element-loading-text="加载中..."
        empty-text="暂无数据"
        fit
        row-key="id"
        hightlight-current-row>
        <u-table-column
          align="left"
          label="姓名" >
          <template slot="header" slot-scope="scope">
            <span class="filter-column">{{ scope.column.label }}</span>
          </template>
          <template slot-scope="scope">
            <span class="filter-column">
              <CheckUserInfo :user-id="scope.row.createUserId" :label="scope.row.createUserName" />
            </span>
          </template>
        </u-table-column>
        <u-table-column
          align="left"
          label="上传时间"
          min-width="160">
          <template slot-scope="scope">
            <span>{{ scope.row.createTime | format('YYYY/MM/DD HH:mm:ss') }}</span>
          </template>
        </u-table-column>
        <u-table-column align="left" label="状态">
          <template slot-scope="scope">
            <div class="flex-center">
              <StatusText :color="['#FD8546','#FF4E5F', '#31CC9C'][scope.row.status]" :text="scope.row.status | statusFilter" />
            </div>
          </template>
        </u-table-column>
        <u-table-column
          align="center"
          label="操作"
          width="110" >
          <template slot-scope="scope">
            <div class="button-text" @click="toggleRowExpansion(scope.row)">查看</div>
          </template>
        </u-table-column>
        <u-table-column type="expand">
          <template slot-scope="props">
            <div class="expand-container">
              <div class="process-list">
                <Title title="导入进度" style="margin: 16px 0" />
                <div v-for="(item, index) in props.row.process" :key="index" class="process-item">
                  <div :class="{'width140':showMobilePage}" class="label">{{ item.processName }}：</div>
                  <div class="content">
                    <img v-if="item.processStatus === 0 || item.processStatus === 1" :src="waitIcon" alt="">
                    <img v-if="item.processStatus === 2" :src="successIcon" alt="">
                    <img v-if="item.processStatus === 3" :src="errorIcon" alt="">
                    {{ item.processStatus | processStatus }}
                  </div>
                </div>
              </div>
              <div :class="{'mobile-result':showMobilePage}" class="result">
                <Title title="导入结果" style="margin: 16px 0"/>
                <div class="process-item">
                  <div class="label">导入结果：</div>
                  <div class="content">{{ props.row.result.importResult || '--' }}</div>
                </div>
                <div class="process-item">
                  <div class="label">完成时间：</div>
                  <div v-if="props.row.result.completeTime" class="content">{{ props.row.result.completeTime | format('YYYY/MM/DD HH:mm') }}</div>
                  <div v-else class="content">--</div>
                </div>
                <div class="process-item">
                  <div class="label">更新的数据范围：</div>
                  <div v-if="showMobilePage">
                    <p>{{ props.row.result.updateRangeStart | format('YYYY/MM/DD HH:mm:ss') }} - </p>
                    <p>{{ props.row.result.updateRangeEnd | format('YYYY/MM/DD HH:mm:ss') }}</p>
                  </div>
                  <div
                    v-else-if="props.row.result.updateRangeStart && props.row.result.updateRangeEnd "
                    class="content">
                    {{ props.row.result.updateRangeStart | format('YYYY/MM/DD HH:mm:ss') }} - {{ props.row.result.updateRangeEnd | format('YYYY/MM/DD HH:mm:ss') }}
                  </div>
                  <div v-else class="content">--</div>
                </div>
                <div class="process-item">
                  <div class="label">更新订单数量：</div>
                  <div v-if="props.row.result.orderNum || props.row.result.orderNum === 0" class="content">{{ props.row.result.orderNum }}</div>
                  <div v-else class="content">--</div>
                </div>
              </div>
            </div>
          </template>
        </u-table-column>
      </u-table>
      <empty-placeholder v-else is-border mode="table" style="margin-top: 24px"/>
      <el-row v-if="showMobilePage" type="flex" justify="left">
        <el-pagination
          v-if="logData.total > 0"
          :current-page.sync="page"
          :page-size="perPage"
          :total="logData.total"
          :small="true"
          :page-sizes="[20, 50, 100, 250, 500]"
          :layout="'total, prev, next, jumper'"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </el-row>
      <el-row v-if="!showMobilePage && logData.items && logData.items.length" type="flex" justify="end">
        <el-pagination
          :current-page="page"
          :page-size="perPage"
          :total="logData.total"
          :page-sizes="[20, 50, 100, 250, 500]"
          layout="total, prev, pager, next, sizes, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </el-row>
    </div>
  </div>
</template>

<script>
import Title from '@/components/Title';
import { format } from '@/filters/date';
import { getUploadLog } from '@/api/commerce';
import EmptyPlaceholder from '@/components/Common/emptyPlaceholder';
import errorIcon from '@/assets/config/upload_error.png';
import successIcon from '@/assets/auditProcess/status4.png';
import waitIcon from '@/assets/config/upload_wait.png';
import mobileTable from '@/mixins/mobileTable';

export default {
  name: 'LogList',
  components: { Title, EmptyPlaceholder },
  filters: {
    format,
    statusFilter(num) {
      const ans = {
        0: '执行中',
        1: '失败',
        2: '成功'
      };
      return ans[num];
    },
    processStatus(num) {
      const ans = {
        0: '未开始',
        1: '导入中...',
        2: '导入完成',
        3: '导入失败'
      };
      return ans[num];
    }
  },
  mixins: [mobileTable],
  data() {
    return {
      errorIcon, successIcon, waitIcon,
      page: 1,
      perPage: 20,
      logData: {},
      timer: null,
      loading: false,
      expandRowKeys: []
    };
  },
  created() {
    this.getLogList(true);
  },
  beforeDestroy() {
    if (this.timer) clearTimeout(this.timer);
  },
  methods: {
    getLogList(reset, isPolling = false) {
      if (reset) this.page = 1;
      if (this.timer) clearTimeout(this.timer);
      if (!isPolling) this.loading = true;
      getUploadLog({ page: this.page, perPage: this.perPage }).then(res => {
        this.loading = false;
        if (res.data) {
          this.logData = res.data;
          if (res.data.items) {
            // 当前页是否有还在执行中的记录，如果有则开启轮询
            const notComplete = res.data.items.some(i => {
              return i.status === 0;
            });
            if (notComplete) {
              this.timer = setTimeout(() => {
                console.log('轮询');
                this.getLogList(false, true);
              }, 20 * 1000);
            }
          }
        }
      }).catch(() => {
        this.loading = false;
      });
    },
    handleSizeChange(val) {
      this.perPage = val;
      this.getLogList(true);
    },
    handleCurrentChange(toPage) {
      this.page = toPage;
      this.getLogList();
    },
    toggleRowExpansion(row) {
      this.$refs.tableRef.toggleRowExpansion(row);
      if (this.expandRowKeys.includes(row.id)) {
        const index = this.expandRowKeys.findIndex(i => i === row.id);
        this.expandRowKeys.splice(index, 1);
      } else {
        this.expandRowKeys.push(row.id);
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.log-list-container {
  margin-top: 32px;
  .table {
    margin-top: 12px;
  }
  &::v-deep {
    .el-table__expanded-cell {
      padding: 12px 0 !important;
    }
    .el-table__expand-column {
      padding:0;
      // border-bottom: none;
      width: 0 !important;
      .cell {
        padding:0;
        display: none;
      }
    }
  }
}
.expand-container {
  display: flex;
  padding-left: 24px;
  background: #fafafc;
  border-radius: 4px;
}
.result {
  flex: 1;
  .process-item .label {
    width: 120px;
  }
}
.mobile-result {
  .process-item .label {
    width: 70px;
    text-align: left;
    margin-right: 6px;
  }
}
.process-list {
  flex:1;
  .process-item .label {
    width: 160px;
  }
  .width140 {
    width: 140px !important;
  }
}
.process-item {
  display: flex;
  margin-bottom: 16px;
  .label {
    text-align: right;
    color: #999;
  }
  .content {
    display: flex;
    align-items: center;
    color: #333;
    img {
      width: 16px;
      margin-right: 4px;
      height: 16px;
    }
  }
}
.el-icon-circle-close {
  color: red;font-size: 14px;
}
.el-icon-circle-check {
  color: #67c23a;font-size: 14px;
}
.title-container {
  display: flex;
  .total {
    font-size: 12px;
    color: #999999;
  }
}
.filter-column {
  padding-left: 14px;
}
</style>
<style lang="scss">
.mobile-table {
  & td {
    height: 40px !important;
  }
  .process-item {
    align-items: center;
  }
}
</style>
